import {
  generateHtmlContent,
  generateIconfontContent,
  generateSvgContent,
  generateSvgsHtmlContent,
  generateSymbolContnt,
} from "./templates";
import { getIconfontContent, getOutputPath } from "./tools";
import { IOptions, ISvgOptions } from "./types";
const fs = require("fs");
const path = require("path");

export function pickSvgs(options: IOptions) {
  options.outputValue = options.outputValue || options.inputValue;
  const { inputValue = "", pick } = options;
  if (!pick || typeof pick !== "string") {
    throw new Error("pick should be a string");
  }

  const inputPath = path.join(
    process.cwd(),
    ...inputValue.split("/").filter(Boolean)
  );
  if (!fs.statSync(inputPath).isFile() && !inputValue.endsWith(".js")) {
    throw new Error("input should be a .js file");
  }
  const { svgId, svgList: oldSvgList } = getIconfontContent(inputPath);
  const pickIds = pick.split(",").filter(Boolean);
  outputFile(svgId, pickIds, oldSvgList, options);
}

// 输出iconfont.js文件
function outputFile(
  svgId: string,
  pickIds: string[],
  svgList: ISvgOptions[],
  options: IOptions
) {
  const { outputValue } = options;
  const pickMap = pickIds.reduce((p, id) => {
    p[id] = true;
    return p;
  }, {} as any);
  const outputPath = getOutputPath(outputValue, "iconfont.js", ".js");
  // 提取剩余的svg
  const restSvgList: ISvgOptions[] = [];
  // 要提取出来的svg
  const pickSvgList: ISvgOptions[] = [];
  svgList.forEach((svg) => {
    if (pickMap[svg.name]) {
      pickSvgList.push(svg);
    } else {
      restSvgList.push(svg);
    }
  });
  // 提取剩余的svg
  const content = generateIconfontContent(
    restSvgList.map(generateSymbolContnt).join(""),
    svgId
  );
  fs.writeFileSync(outputPath, content);
  const html = generateHtmlContent(restSvgList.map((item) => item.name));
  const htmlPath = path.join(path.parse(outputPath).dir, "index.html");
  fs.writeFileSync(htmlPath, html);
  // 被提取的svg文件
  pickSvgList.forEach((svg) => {
    const { content, name, viewBox } = svg;
    const svgPath = path.join(path.parse(outputPath).dir, `${name}.svg`);
    fs.writeFileSync(svgPath, generateSvgContent(content, viewBox));
  });
  const svgHtmlPath = path.join(path.parse(outputPath).dir, "svgIndex.html");
  fs.writeFileSync(
    svgHtmlPath,
    generateSvgsHtmlContent(pickSvgList.map((item) => item.name))
  );
}
